package co.baiku.boot.jpush;

import cn.jiguang.common.ClientConfig;
import cn.jiguang.common.connection.HttpProxy;
import cn.jiguang.common.resp.APIConnectionException;
import cn.jiguang.common.resp.APIRequestException;
import cn.jpush.api.JPushClient;
import cn.jpush.api.push.PushResult;
import cn.jpush.api.push.model.Options;
import cn.jpush.api.push.model.Platform;
import cn.jpush.api.push.model.PushPayload;
import cn.jpush.api.push.model.audience.Audience;
import cn.jpush.api.push.model.notification.AndroidNotification;
import cn.jpush.api.push.model.notification.IosAlert;
import cn.jpush.api.push.model.notification.IosNotification;
import cn.jpush.api.push.model.notification.Notification;
import co.baiku.boot.common.tools.JsonTools;
import co.baiku.boot.common.tools.StringTools;
import co.baiku.boot.config.JPushConfig;
import co.baiku.boot.config.JpushProxyConfig;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.InitializingBean;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.autoconfigure.condition.ConditionalOnProperty;
import org.springframework.stereotype.Component;

@Component
@ConditionalOnProperty("ajavaer.jpush.app-key")
public class Jpush implements InitializingBean {
    private static final Logger log = LoggerFactory.getLogger(Jpush.class);

    private JPushConfig pushConfig;
    private JPushClient pushClient;

    public Jpush() {

    }

    @Autowired
    public Jpush(JPushConfig jPushConfig) {
        this.pushConfig = jPushConfig;
    }

    /**
     * 发送通知
     *
     * @param
     * @return
     */
    public void sendPush(JPushRequest request) {
        PushPayload payload = buildPushObjectAndroidIos(request);
        try {
            PushResult result = pushClient.sendPush(payload);
            log.debug("push message pushTitle:{}, result:{}", request.getTitle(), result);
        } catch (APIConnectionException e) {
            log.error("Connection error. Should retry later. sendNo:" + payload.getSendno(), e);
        } catch (APIRequestException e) {
            log.error("Error response from JPush server. error:" + JsonTools.beanToJson(e), e);
        }
    }

    /**
     * 发送参数设置
     *
     * @param
     * @return
     */
    private PushPayload buildPushObjectAndroidIos(JPushRequest bean) {
        Audience audience = Audience.registrationId(bean.getRegistrationId());
        IosAlert alert = IosAlert.newBuilder()
                .setTitleAndBody(bean.getTitle(), bean.getSubTitle(), bean.getContent())
                .setActionLocKey("PLAY")
                .build();
        return PushPayload.newBuilder()
                .setPlatform(Platform.android_ios())
                .setAudience(audience)
                .setNotification(Notification.newBuilder()
                        .setAlert(bean.getContent())
                        .addPlatformNotification(AndroidNotification.newBuilder()
                                .setTitle(bean.getTitle())
                                .addExtras(bean.getExtras())
                                .build())
                        .addPlatformNotification(IosNotification.newBuilder()
                                .incrBadge(1)
                                .setAlert(alert)
                                .setMutableContent(true)
                                .setContentAvailable(false)
                                .addExtras(bean.getExtras())
                                .setSound("default")
                                .build())
                        .build())
                .setOptions(Options.newBuilder()
                        .setApnsProduction(pushConfig.getApnsProduction())
                        .setTimeToLive(864000)
                        .build())
                .build();
    }


    @Override
    public void afterPropertiesSet() throws Exception {
        ClientConfig clientConfig = ClientConfig.getInstance();
        HttpProxy httpProxy = null;
        JpushProxyConfig jpushProxyConfig = pushConfig.getProxy();
        if (jpushProxyConfig != null && StringTools.isNotBlank(jpushProxyConfig.getHost())) {
            if (!jpushProxyConfig.isAuthenticationNeeded()) {
                httpProxy = new HttpProxy(jpushProxyConfig.getHost(), jpushProxyConfig.getPort());
            } else {
                httpProxy = new HttpProxy(jpushProxyConfig.getHost(), jpushProxyConfig.getPort(), jpushProxyConfig.getUsername(), jpushProxyConfig.getPassword());
            }
            log.debug("jpush init with proxy");
        }
        pushClient = new JPushClient(pushConfig.getMasterSecret(), pushConfig.getAppKey(), httpProxy, clientConfig);
        log.debug("jpush init success");
    }
}
